<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" placeholder="请输入用户名">
        <template #prefix>
          <el-icon class="el-input__icon"><user /></el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" show-password autocomplete="new-password">
        <template #prefix>
          <el-icon class="el-input__icon"><lock /></el-icon>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button :icon="CircleClose" round @click="resetForm(loginFormRef)" size="large">重置</el-button>
    <el-button :icon="UserFilled" round @click="login(loginFormRef)" size="large" type="primary" :loading="loading">
      登录
    </el-button>
  </div>
  <div class="resetPassword">
    <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
    <el-link type="primary" @click="goPassword">修改密码</el-link>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { storeToRefs } from "pinia";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import { getTimeState } from "@/utils";
import { Login } from "@/api/interface";
import { useTheme } from "@/hooks/useTheme";
import { ElNotification } from "element-plus";
import { getAllUserInfo } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useAppStore } from "@/stores/modules/app";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { useDictionryStore } from "@/stores/modules/dictionary";
import { useGlobalStore } from "@/stores/modules/global";
import { useFondsStore } from "@/stores/modules/fonds";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import md5 from "js-md5";
import ACrypto from "@/utils/crypto";
import useCurrentInstance from "@/utils/useCurrentInstance";
import axios from "axios";
import { useScrollbar } from "@/hooks/useScrollbar";

const { proxy } = useCurrentInstance();
const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();
const dictionryStore = useDictionryStore();
const appStore = useAppStore();
const globalStore = useGlobalStore();
const fondsStore = useFondsStore();
const { setScrollbarConfig, initScrollbar } = useScrollbar();
const {
  layout,
  primary,
  isGrey,
  isWeak,
  asideInverted,
  headerInverted,
  isCollapse,
  breadcrumb,
  breadcrumbIcon,
  tabs,
  tabsIcon,
  footer,
  continuousSubmission,
  fondsRouter,
  showChild,
  pageSize,
  pageSpace,
  showOvertime,
  overtime,
  indexKey,
  lastKey,
  prevKey,
  nextKey
} = storeToRefs(globalStore);

const loginFormRef = ref<FormInstance>();
const loginRules = reactive<FormRules>({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  username: "",
  password: "",
  rememberMe: false
});

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      const data = await proxy.$vueAxios.post(
        "MasterBaseUsers/Validate",
        {
          u_Name: ACrypto.setSS(loginForm.username),
          u_PWD: md5(loginForm.password)
        },
        { noLoading: true }
      );
      if (data.Mark) {
        // 将账号密码缓存到本地
        if (loginForm.rememberMe) {
          localStorage.setItem("username", ACrypto.setSS(loginForm.username));
          localStorage.setItem("password", ACrypto.setSS(loginForm.password));
          localStorage.setItem("rememberMe", "1");
        } else {
          localStorage.removeItem("username");
          localStorage.removeItem("password");
          localStorage.removeItem("rememberMe");
        }
        // 存储token
        userStore.setToken(data.Model.U_Token);
        // 存储个人信息
        userStore.setUserInfo(data.Model);
        // 设置个人配置
        if (data.Model.U_InterfaceSettings) {
          const setting = JSON.parse(data.Model.U_InterfaceSettings);
          layout.value = setting.layout;
          primary.value = setting.primary;
          isGrey.value = setting.isGrey;
          asideInverted.value = setting.asideInverted;
          headerInverted.value = setting.headerInverted;
          isCollapse.value = setting.isCollapsibleMenu;
          breadcrumb.value = setting.isCrumbs;
          breadcrumbIcon.value = setting.isBreadcrumbIcon;
          tabs.value = setting.isTabBar;
          tabsIcon.value = setting.isTabBarIcon;
          footer.value = setting.isFooter;
          continuousSubmission.value = setting.isContinuousEmission;
          fondsRouter.value = setting.isFullRoute;
          showChild.value = setting.isDisplayChild;
          pageSpace.value = setting.pageSpacing;
          pageSize.value = setting.loadNum;
          showOvertime.value = setting.showOvertime;
          overtime.value = setting.overtime;
          indexKey.value = setting.indexKey;
          lastKey.value = setting.lastKey;
          prevKey.value = setting.prevKey;
          nextKey.value = setting.nextKey;
          isGrey.value = setting.isGrey;
          isWeak.value = setting.isWeak;
          // 设置滚动条配置
          if (setting.scrollbarConfig) {
            setScrollbarConfig(setting.scrollbarConfig);
          }
          // 设置Splite位置
          if (setting.splitpanesPos) {
            globalStore.setGlobalState("splitpanesPos", setting.splitpanesPos);
          }
        }
        // 设置主题色
        const { changePrimary, changeGreyOrWeak, setAsideTheme, setHeaderTheme } = useTheme();
        changePrimary(primary.value);
        // 初始化滚动条样式
        initScrollbar();
        const Res = await axios.get("/config.json");
        appStore.setHideRouter(Res.data.hideRouter);
        // 存储全宗
        await fondsStore.setFondsData();
        // 2.添加动态路由
        await initDynamicRouter();
        // 存储字典数据
        await dictionryStore.setDictionaryObj();
        // 存储系统参数
        await appStore.setSysConfigData();
        // 获取所有用户数据
        await getAllUserInfo();

        // 3.清空 tabs、keepAlive 数据
        tabsStore.closeMultipleTab();
        keepAliveStore.setKeepAliveName();
        // 4.跳转到首页
        router.push(HOME_URL);
        ElNotification({
          title: getTimeState(),
          message: `欢迎登录 ${loginForm.username}`,
          type: "success",
          duration: 3000
        });
      } else {
        proxy.$message.warning(data.Msg);
      }
    } finally {
      loading.value = false;
    }
  });
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
// 修改密码
const goPassword = () => {
  router.push("resetPassword");
};
onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
  // 获取用户名密码缓存
  const savedUsername = localStorage.getItem("username");
  const savedPassword = localStorage.getItem("password");
  loginForm.username = savedUsername ? ACrypto.getSS(savedUsername) : "";
  loginForm.password = savedPassword ? ACrypto.getSS(savedPassword) : "";
  const savedRemember = localStorage.getItem("rememberMe");
  loginForm.rememberMe = savedRemember === "1" || !!savedUsername || !!savedPassword;
});
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
